package test;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

//测试ReetrantWriteAndReadLock的使用
public class ReadAndWriteLock {

    private static final HashMap<String, Object> redis = new HashMap<>();
    private static ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock();

    public void put(String key, Object val) {
        String id = Thread.currentThread().getId() + "";
        redis.put(id, id);
    }

    public Object get(String key) {
        return redis.get(key);
    }

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                rwlock.writeLock().lock();
                System.out.println("线程" + Thread.currentThread().getId() + "开始写入");
                try {
                    TimeUnit.SECONDS.sleep(1);
                    redis.put(Thread.currentThread().getId() + "", Thread.currentThread().getId());
                    System.out.println("线程" + Thread.currentThread().getId() + "写入finished");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    rwlock.writeLock().unlock();
                }

            }).start();
        }

        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                try {
                    rwlock.readLock().lock();

                    System.out.println("线程" + Thread.currentThread().getId() + "开始读取");
                    System.out.println("线程" + Thread.currentThread().getId() + "读取finished: "
                            + redis.get(Thread.currentThread().getId() + ""));
                } catch (Exception e) {

                } finally {
                    rwlock.readLock().unlock();
                }

            }).start();
        }
    }
}
